package com.xfcycle.zebrabikegp.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.constant.BluetoothDeviceConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;

/**
 * 车辆报警设置  实际上是通过开关GSM状态实现的
 */
public class BsAlarmActivity extends RootActivity {

    private static final String TAG = "BsAlarm";

    private RelativeLayout rl_cover;
    private ImageView iv_alarm_back;
    private Switch switch_alarm_state;
    private Button btn_reboot_bike;
    private Button btn_reset_bike;

    private HandleDataByBLEUtil handleDataByBLEUtil;

    //记录按下之前报警的状态
    private boolean isAlarmStateChecked;
    private AlarmHandleDataFromBleReceiver alarmHandleDataFromBleReceiver;

    //判断是手动改变 还是 代码改变
    private boolean isManualCheck = false;

    //重启下底板弹出框
    private AlertDialog rebootDialog;

    //恢复出厂设置弹出框
    private AlertDialog resetDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bs_alarm);

        initView();
        initViewListener();
        setViewContent();
    }

    @Override
    protected void onResume() {
        super.onResume();

        //注册广播
        alarmHandleDataFromBleReceiver = new AlarmHandleDataFromBleReceiver();
        registBroadcastReceiverAtActivity(alarmHandleDataFromBleReceiver, BluetoothDeviceConstant.GET_DATA_FROM_BLUETOOTH_BROADCAST_RECEIVER_ACTION);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //回收广播接收者
        unregisterReceiver(alarmHandleDataFromBleReceiver);
    }

    /***********************************************************************************************/
    /**                                 初始化控件对象 监听 控件内容方法                             **/
    /***********************************************************************************************/

    private void initView() {
        iv_alarm_back = (ImageView) findViewById(R.id.iv_alarm_back);
        switch_alarm_state = (Switch) findViewById(R.id.switch_alarm_state);
        btn_reboot_bike = (Button) findViewById(R.id.btn_reboot_bike);
        btn_reset_bike = (Button) findViewById(R.id.btn_reset_bike);
        rl_cover = (RelativeLayout) findViewById(R.id.rl_cover);

        handleDataByBLEUtil = HandleDataByBLEUtil.getInstance(this, -1);

        //初始化重启下底板弹出框
        initRebootDialog();

        //初始化出厂设置弹出框
        initResetDialog();
    }

    private void initViewListener() {
        //回退事件监听
        iv_alarm_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //监听是否手动改变
        switch_alarm_state.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        isManualCheck = true;
                        break;
                }
                return false;
            }
        });

        //开关GSM
        switch_alarm_state.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAlarmStateChecked = isChecked;

                if (!isManualCheck) {
                    return;
                }

                rl_cover.setVisibility(View.VISIBLE);

                Log.w(TAG, "onCheckedChanged: -------------------- 当前GSM选择状态：" + isChecked);

                if (isChecked) {
                    //打开GSM
                    handleDataByBLEUtil.sendDataToDevice("s|8,1");
                    return;
                }
                //关闭GSM
                handleDataByBLEUtil.sendDataToDevice("s|8,2");
            }
        });

        //重启下底板
        btn_reboot_bike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != rebootDialog) {
                    rebootDialog.show();
                }
            }
        });

        //恢复出厂设置
        btn_reset_bike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != resetDialog) {
                    resetDialog.show();
                }
            }
        });
    }

    private void setViewContent() {
        rl_cover.setVisibility(View.VISIBLE);

        //查询GSM状态
        handleDataByBLEUtil.sendDataToDevice("s|8,0");
    }

    /***********************************************************************************************/
    /**                                  初始化修改服务器弹出框                                     **/
    /***********************************************************************************************/
    /**
     * 初始化重启下底板消息弹窗
     */
    private void initRebootDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Notice");
        builder.setMessage("Reboot system may take few minutes.");

        //取消重启下底板
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (null != rebootDialog) {
                    rebootDialog.dismiss();
                }
            }
        });

        //确定重启下底板
        builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                rl_cover.setVisibility(View.VISIBLE);
                handleDataByBLEUtil.sendDataToDevice("AT+RST1");
            }
        });

        //创建弹出框
        rebootDialog = builder.create();
    }

    /**
     * 初始化恢复出厂设置消息弹窗
     */
    private void initResetDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Notice");
        builder.setMessage("This operation will clear all of the setting and set back to default.");

        //取消重启下底板
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (null != resetDialog) {
                    resetDialog.dismiss();
                }
            }
        });

        //确定重启下底板
        builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                rl_cover.setVisibility(View.VISIBLE);
                handleDataByBLEUtil.sendDataToDevice("AT+FACTORY");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SystemClock.sleep(10 * 1000);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                rl_cover.setVisibility(View.GONE);
                            }
                        });
                    }
                }).start();
            }
        });

        //创建弹出框
        resetDialog = builder.create();
    }
    /***********************************************************************************************/
    /**                                 自定义广播接收者类                                          **/
    /***********************************************************************************************/

    /**
     * 广播接收者类，负责接收从蓝牙发出的数据并对其进行处理
     */
    class AlarmHandleDataFromBleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("result");

            Log.w(TAG, "onReceive: ------------- " + result);

            isManualCheck = false;

            //打开GSM
            if (result.contains("^s|8,1")) {
                modifyGsmSwitch(context, true);
                rl_cover.setVisibility(View.GONE);
                return;
            }

            //关闭GSM
            if (result.contains("^s|8,2")) {
                modifyGsmSwitch(context, false);
                rl_cover.setVisibility(View.GONE);
                return;
            }

            //重启下底板
            if (result.contains("RST1")) {
                rl_cover.setVisibility(View.GONE);
                return;
            }

            //恢复出厂设置
            if (result.contains("FACTORY")) {
                rl_cover.setVisibility(View.GONE);
                return;
            }

            //修改GSM至初始状态
            switch_alarm_state.setChecked(!isAlarmStateChecked);
        }
    }

    /**
     * 展示查询及修改GSM结果
     */
    private void modifyGsmSwitch(Context context, boolean isCheck) {
        //查询结果展示
        if (!isManualCheck) {
            switch_alarm_state.setChecked(isCheck);
            return;
        }

        //修改结果展示
        Toast.makeText(context.getApplicationContext(), ToastConstant.MODIFY_HEADLIGHT_STATE_SUCCESS, Toast.LENGTH_SHORT).show();
    }
}
